/**
 * 聊天室 WebSocket 端点
 */
let time = 0;
const connections = [];

/**
 * 处理聊天室 WebSocket 连接
 * @param {Object} request - WebSocket 请求对象
 */
function handleChatRequest(request) {
  console.log(`聊天室收到连接请求，来源: ${request.origin}`);
  
  // 接受连接
  const connection = request.accept(null, request.origin);
  connections.push(connection);
  console.log(`${new Date().toLocaleDateString()} 聊天室建立新连接，当前连接数: ${connections.length}`);
  
  // 发送欢迎消息
  connection.sendUTF(JSON.stringify({
    type: "system",
    message: "欢迎来到聊天室！"
  }));
  
  // 心跳检测
  const heartbeatInterval = setInterval(() => {
    if (connection.connected) {
      connection.sendUTF(JSON.stringify({
        type: "heartbeat",
        value: "心跳💓" + time++
      }));
    } else {
      clearInterval(heartbeatInterval);
    }
  }, 30000);
  
  // 处理消息
  connection.on("message", (message) => {
    if (message.type === "utf8") {
      console.log(`聊天室收到消息: ${message.utf8Data}`);
      
      // 广播消息给所有客户端
      const messageData = message.utf8Data;
      connections.forEach((client) => {
        if (client !== connection && client.connected) {
          client.sendUTF(messageData);
        }
      });
    }
  });
  
  // 处理连接关闭
  connection.on("close", (reasonCode, description) => {
    // 从连接列表中移除
    const index = connections.indexOf(connection);
    if (index !== -1) {
      connections.splice(index, 1);
    }
    
    console.log(`${new Date().toLocaleDateString()} 聊天室连接关闭，当前连接数: ${connections.length}`);
    clearInterval(heartbeatInterval);
  });
}

module.exports = handleChatRequest;